package cp

import (
	"fmt"
	"gitee.com/getcharzp/light-ftp/define"
	"io"
	"os"
	"path/filepath"
	"strings"
)

func Cp(src, dst string) {
	// upload dst -> [site]:[remote path]
	// download src -> [site]:[remote path]
	var (
		siteName string
		op       string // download upload
	)

	srcIndex := strings.Index(src, ":")
	dstIndex := strings.Index(dst, ":")
	if srcIndex == -1 && dstIndex == -1 {
		fmt.Println("远程路径格式错误,格式为 -> [站点名称]:[远程路径]")
		os.Exit(1)
	} else if srcIndex != -1 && dstIndex != -1 {
		fmt.Println("有且必须只有一个为远程路径")
		os.Exit(1)
	}

	if srcIndex != -1 {
		siteName = src[:srcIndex]
		src = src[srcIndex+1:]
		op = "download"
	} else {
		siteName = dst[:dstIndex]
		dst = dst[dstIndex+1:]
		op = "upload"
	}

	sysConfig := &define.SysConfig{}
	if err := sysConfig.Read(); err != nil {
		fmt.Println("light ftp config error.", err)
		os.Exit(1)
	}
	for _, site := range sysConfig.Sites {
		if site.Name == siteName {
			client, err := define.NewClient(site)
			if err != nil {
				fmt.Println("初始化客户端失败", err)
				os.Exit(1)
			}
			if op == "upload" {
				f, err := os.Open(src)
				if err != nil {
					fmt.Println("打开文件失败", err)
					os.Exit(1)
				}
				if err := client.Conn.Stor(dst[dstIndex+1:]+"/"+filepath.Base(src), f); err != nil {
					fmt.Println("上传文件失败", err)
					os.Exit(1)
				}
				fmt.Println("上传成功")
				os.Exit(0)
			} else {
				res, err := client.Conn.Retr(src)
				if err != nil {
					fmt.Println("下载文件失败", err)
					os.Exit(1)
				}
				f, err := os.Create(filepath.Join(dst, filepath.Base(src)))
				if err != nil {
					fmt.Println("创建文件失败", err)
					os.Exit(1)
				}
				if _, err := io.Copy(f, res); err != nil {
					fmt.Println("写入文件失败", err)
					os.Exit(1)
				}
			}
		}
	}

}
